<template>
  <view class="face-test-panel">
    <view class="panel-header">
      <text class="panel-title">人脸识别测试面板</text>
      <text class="panel-subtitle">测试人脸识别各项功能</text>
    </view>

    <view class="test-section">
      <view class="section-title">1. 服务健康检查</view>
      <view class="test-item">
        <button class="test-btn" @click="testHealthCheck" :disabled="isProcessing">
          <text class="btn-text">检查后端服务状态</text>
        </button>
        <view class="test-result" v-if="healthResult">
          <text class="result-status" :class="{ success: healthResult.success, error: !healthResult.success }">
            {{ healthResult.success ? '✅ 正常' : '❌ 异常' }}
          </text>
          <text class="result-message">{{ healthResult.message }}</text>
        </view>
      </view>
    </view>

    <view class="test-section">
      <view class="section-title">2. 人脸检测测试</view>
      <view class="test-item">
        <button class="test-btn" @click="testFaceDetection" :disabled="isProcessing">
          <text class="btn-text">测试人脸检测</text>
        </button>
        <view class="test-result" v-if="detectResult">
          <text class="result-status" :class="{ success: detectResult.success, error: !detectResult.success }">
            {{ detectResult.success ? '✅ 检测成功' : '❌ 检测失败' }}
          </text>
          <text class="result-message">{{ detectResult.message }}</text>
          <text class="result-detail" v-if="detectResult.data">
            检测到 {{ detectResult.data.FaceNum }} 个人脸
          </text>
        </view>
      </view>
    </view>

    <view class="test-section">
      <view class="section-title">3. 人脸注册测试</view>
      <view class="test-item">
        <input class="test-input" v-model="registerForm.personName" placeholder="请输入姓名" />
        <input class="test-input" v-model="registerForm.personId" placeholder="请输入用户ID" />
        <input class="test-input" v-model="registerForm.phone" placeholder="请输入手机号（可选）" />
        <input class="test-input" v-model="registerForm.password" placeholder="请输入密码（可选）" type="password" />
        <button class="test-btn" @click="testFaceRegister" :disabled="isProcessing">
          <text class="btn-text">测试人脸注册</text>
        </button>
        <view class="test-result" v-if="registerResult">
          <text class="result-status" :class="{ success: registerResult.success, error: !registerResult.success }">
            {{ registerResult.success ? '✅ 注册成功' : '❌ 注册失败' }}
          </text>
          <text class="result-message">{{ registerResult.message }}</text>
        </view>
      </view>
    </view>

    <view class="test-section">
      <view class="section-title">4. 人脸登录测试</view>
      <view class="test-item">
        <button class="test-btn" @click="testFaceLogin" :disabled="isProcessing">
          <text class="btn-text">测试人脸登录</text>
        </button>
        <view class="test-result" v-if="loginResult">
          <text class="result-status" :class="{ success: loginResult.success, error: !loginResult.success }">
            {{ loginResult.success ? '✅ 登录成功' : '❌ 登录失败' }}
          </text>
          <text class="result-message">{{ loginResult.message }}</text>
          <text class="result-detail" v-if="loginResult.data">
            相似度: {{ loginResult.data.similarity }}%
          </text>
        </view>
      </view>
    </view>

    <view class="test-section">
      <view class="section-title">5. 创建人脸库</view>
      <view class="test-item">
        <button class="test-btn" @click="testCreateFaceGroup" :disabled="isProcessing">
          <text class="btn-text">创建默认人脸库</text>
        </button>
        <view class="test-result" v-if="groupResult">
          <text class="result-status" :class="{ success: groupResult.success, error: !groupResult.success }">
            {{ groupResult.success ? '✅ 创建成功' : '❌ 创建失败' }}
          </text>
          <text class="result-message">{{ groupResult.message }}</text>
        </view>
      </view>
    </view>

    <view class="test-section">
      <view class="section-title">6. 摄像头测试</view>
      <view class="test-item">
        <button class="test-btn" @click="testCamera" :disabled="isProcessing">
          <text class="btn-text">测试摄像头捕获</text>
        </button>
        <view class="test-result" v-if="cameraResult">
          <text class="result-status" :class="{ success: cameraResult.success, error: !cameraResult.success }">
            {{ cameraResult.success ? '✅ 捕获成功' : '❌ 捕获失败' }}
          </text>
          <text class="result-message">{{ cameraResult.message }}</text>
          <text class="result-detail" v-if="cameraResult.imageSize">
            图像大小: {{ cameraResult.imageSize }} 字节
          </text>
        </view>
      </view>
    </view>

    <view class="test-summary">
      <view class="summary-title">测试总结</view>
      <view class="summary-item">
        <text class="summary-label">后端服务:</text>
        <text class="summary-value" :class="{ success: healthResult?.success, error: healthResult && !healthResult.success }">
          {{ healthResult ? (healthResult.success ? '正常' : '异常') : '未测试' }}
        </text>
      </view>
      <view class="summary-item">
        <text class="summary-label">人脸检测:</text>
        <text class="summary-value" :class="{ success: detectResult?.success, error: detectResult && !detectResult.success }">
          {{ detectResult ? (detectResult.success ? '正常' : '异常') : '未测试' }}
        </text>
      </view>
      <view class="summary-item">
        <text class="summary-label">人脸注册:</text>
        <text class="summary-value" :class="{ success: registerResult?.success, error: registerResult && !registerResult.success }">
          {{ registerResult ? (registerResult.success ? '正常' : '异常') : '未测试' }}
        </text>
      </view>
      <view class="summary-item">
        <text class="summary-label">人脸登录:</text>
        <text class="summary-value" :class="{ success: loginResult?.success, error: loginResult && !loginResult.success }">
          {{ loginResult ? (loginResult.success ? '正常' : '异常') : '未测试' }}
        </text>
      </view>
    </view>

    <view class="panel-actions">
      <button class="action-btn primary" @click="runAllTests" :disabled="isProcessing">
        <text class="btn-text">运行所有测试</text>
      </button>
      <button class="action-btn secondary" @click="clearResults">
        <text class="btn-text">清除结果</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { 
  healthCheck, 
  detectFace, 
  faceRegister, 
  faceLogin, 
  createFaceGroup,
  type FaceDetectResult,
  type FaceLoginResult,
  type FaceRegisterResult,
  type HealthCheckResult
} from '@/api/zjx-face'

// 响应式数据
const isProcessing = ref(false)
const healthResult = ref<HealthCheckResult | null>(null)
const detectResult = ref<FaceDetectResult | null>(null)
const registerResult = ref<FaceRegisterResult | null>(null)
const loginResult = ref<FaceLoginResult | null>(null)
const groupResult = ref<any>(null)
const cameraResult = ref<any>(null)

// 注册表单
const registerForm = ref({
  personName: '测试用户',
  personId: 'test_user_' + Date.now(),
  phone: '',
  password: ''
})

// 测试健康检查
const testHealthCheck = async () => {
  try {
    isProcessing.value = true
    healthResult.value = await healthCheck()
  } catch (error) {
    console.error('健康检查失败:', error)
    healthResult.value = {
      success: false,
      message: '健康检查失败: ' + (error instanceof Error ? error.message : '未知错误'),
      timestamp: new Date().toISOString()
    }
  } finally {
    isProcessing.value = false
  }
}

  // 测试人脸检测
  const testFaceDetection = async () => {
    try {
      isProcessing.value = true
      
      // 创建一个有效的测试图像
      const testCanvas = document.createElement('canvas')
      testCanvas.width = 640
      testCanvas.height = 480
      const testCtx = testCanvas.getContext('2d')
      
      if (testCtx) {
        testCtx.fillStyle = '#2a2a2a'
        testCtx.fillRect(0, 0, 640, 480)
        testCtx.fillStyle = '#00ff00'
        testCtx.font = '24px Arial'
        testCtx.textAlign = 'center'
        testCtx.fillText('人脸检测测试图像', 320, 240 - 20)
        testCtx.fillText('用于API测试', 320, 240 + 20)
        
        const testImage = testCanvas.toDataURL('image/jpeg', 0.8)
        detectResult.value = await detectFace(testImage)
      } else {
        throw new Error('无法创建测试图像')
      }
    } catch (error) {
      console.error('人脸检测测试失败:', error)
      detectResult.value = {
        success: false,
        message: '人脸检测测试失败: ' + (error instanceof Error ? error.message : '未知错误')
      }
    } finally {
      isProcessing.value = false
    }
  }

  // 测试人脸注册
  const testFaceRegister = async () => {
    try {
      isProcessing.value = true
      
      if (!registerForm.value.personName || !registerForm.value.personId) {
        registerResult.value = {
          success: false,
          message: '请填写姓名和用户ID'
        }
        return
      }
      
      // 创建一个有效的测试图像
      const testCanvas = document.createElement('canvas')
      testCanvas.width = 640
      testCanvas.height = 480
      const testCtx = testCanvas.getContext('2d')
      
      if (testCtx) {
        testCtx.fillStyle = '#2a2a2a'
        testCtx.fillRect(0, 0, 640, 480)
        testCtx.fillStyle = '#00ff00'
        testCtx.font = '24px Arial'
        testCtx.textAlign = 'center'
        testCtx.fillText('人脸注册测试图像', 320, 240 - 20)
        testCtx.fillText(registerForm.value.personName, 320, 240 + 20)
        
        const testImage = testCanvas.toDataURL('image/jpeg', 0.8)
        registerResult.value = await faceRegister(
          testImage,
          registerForm.value.personName,
          registerForm.value.personId,
          undefined,
          registerForm.value.phone || undefined,
          registerForm.value.password || undefined
        )
      } else {
        throw new Error('无法创建测试图像')
      }
    } catch (error) {
      console.error('人脸注册测试失败:', error)
      registerResult.value = {
        success: false,
        message: '人脸注册测试失败: ' + (error instanceof Error ? error.message : '未知错误')
      }
    } finally {
      isProcessing.value = false
    }
  }

  // 测试人脸登录
  const testFaceLogin = async () => {
    try {
      isProcessing.value = true
      
      // 创建一个有效的测试图像
      const testCanvas = document.createElement('canvas')
      testCanvas.width = 640
      testCanvas.height = 480
      const testCtx = testCanvas.getContext('2d')
      
      if (testCtx) {
        testCtx.fillStyle = '#2a2a2a'
        testCtx.fillRect(0, 0, 640, 480)
        testCtx.fillStyle = '#00ff00'
        testCtx.font = '24px Arial'
        testCtx.textAlign = 'center'
        testCtx.fillText('人脸登录测试图像', 320, 240 - 20)
        testCtx.fillText('用于API测试', 320, 240 + 20)
        
        const testImage = testCanvas.toDataURL('image/jpeg', 0.8)
        loginResult.value = await faceLogin(testImage)
      } else {
        throw new Error('无法创建测试图像')
      }
    } catch (error) {
      console.error('人脸登录测试失败:', error)
      loginResult.value = {
        success: false,
        message: '人脸登录测试失败: ' + (error instanceof Error ? error.message : '未知错误')
      }
    } finally {
      isProcessing.value = false
    }
  }

// 测试创建人脸库
const testCreateFaceGroup = async () => {
  try {
    isProcessing.value = true
    groupResult.value = await createFaceGroup()
  } catch (error) {
    console.error('创建人脸库测试失败:', error)
    groupResult.value = {
      success: false,
      message: '创建人脸库测试失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  } finally {
    isProcessing.value = false
  }
}

// 测试摄像头
const testCamera = async () => {
  try {
    isProcessing.value = true
    
    // 尝试启动摄像头
    const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: 'user',
        width: { ideal: 640 },
        height: { ideal: 480 }
      },
      audio: false
    })
    
    // 创建视频元素
    const video = document.createElement('video')
    video.srcObject = stream
    video.autoplay = true
    video.muted = true
    video.playsInline = true
    
    // 等待视频加载
    await new Promise((resolve) => {
      video.onloadedmetadata = resolve
    })
    
    // 创建canvas捕获图像
    const canvas = document.createElement('canvas')
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    const ctx = canvas.getContext('2d')
    
    if (ctx) {
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
      const imageData = canvas.toDataURL('image/jpeg', 0.8)
      
      cameraResult.value = {
        success: true,
        message: '摄像头测试成功',
        imageSize: imageData.length
      }
    } else {
      throw new Error('无法获取canvas上下文')
    }
    
    // 停止摄像头
    stream.getTracks().forEach(track => track.stop())
    
  } catch (error) {
    console.error('摄像头测试失败:', error)
    cameraResult.value = {
      success: false,
      message: '摄像头测试失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  } finally {
    isProcessing.value = false
  }
}

// 运行所有测试
const runAllTests = async () => {
  try {
    isProcessing.value = true
    
    // 按顺序运行测试
    await testHealthCheck()
    await testCreateFaceGroup()
    await testFaceDetection()
    await testFaceRegister()
    await testFaceLogin()
    await testCamera()
    
    uni.showToast({
      title: '所有测试完成',
      icon: 'success'
    })
  } catch (error) {
    console.error('运行所有测试失败:', error)
    uni.showToast({
      title: '测试过程中出现错误',
      icon: 'error'
    })
  } finally {
    isProcessing.value = false
  }
}

// 清除结果
const clearResults = () => {
  healthResult.value = null
  detectResult.value = null
  registerResult.value = null
  loginResult.value = null
  groupResult.value = null
  cameraResult.value = null
}
</script>

<style scoped>
.face-test-panel {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.panel-header {
  text-align: center;
  margin-bottom: 30px;
}

.panel-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8px;
}

.panel-subtitle {
  font-size: 14px;
  color: #666;
  display: block;
}

.test-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  border-bottom: 2px solid #007aff;
  padding-bottom: 8px;
}

.test-item {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.test-input {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
  background: #f9f9f9;
}

.test-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 20px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.test-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.test-btn:not(:disabled):hover {
  background: #0056cc;
}

.test-result {
  padding: 12px;
  border-radius: 8px;
  background: #f8f9fa;
  border-left: 4px solid #007aff;
}

.result-status {
  font-weight: bold;
  display: block;
  margin-bottom: 5px;
}

.result-status.success {
  color: #28a745;
}

.result-status.error {
  color: #dc3545;
}

.result-message {
  color: #666;
  font-size: 14px;
  display: block;
  margin-bottom: 5px;
}

.result-detail {
  color: #007aff;
  font-size: 12px;
  display: block;
}

.test-summary {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.summary-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  border-bottom: 2px solid #28a745;
  padding-bottom: 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.summary-label {
  font-weight: 500;
  color: #333;
}

.summary-value {
  font-weight: bold;
}

.summary-value.success {
  color: #28a745;
}

.summary-value.error {
  color: #dc3545;
}

.panel-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.action-btn {
  flex: 1;
  border: none;
  border-radius: 8px;
  padding: 15px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn.primary {
  background: #007aff;
  color: white;
}

.action-btn.primary:hover {
  background: #0056cc;
}

.action-btn.secondary {
  background: #6c757d;
  color: white;
}

.action-btn.secondary:hover {
  background: #545b62;
}

.action-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style>
